//
//  GetUserStationService.m
//  XTCloud
//
//  Created by QA on 2017/2/7.
//  Copyright © 2017年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "GetUserStationService.h"
#import "WebServiceCommonRequest.h"
#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

static GetUserStationService *sharedMenuService = nil;
@implementation GetUserStationService

+ (GetUserStationService*)sharedService
{
    @synchronized(self){
        if (sharedMenuService == nil){
            sharedMenuService = [[self alloc] init];
        }
    }
    return sharedMenuService;
}

//获取所有站点信息
- (NSArray *)getAllStationToArray
{
    return [StationInfoEntity MR_findAllSortedBy:@"order" ascending:YES];
}

//获取选中站点信息
- (StationInfoEntity*)getSelectStationEntity
{
    NSPredicate *predicateMain = [NSPredicate predicateWithFormat:@"isSelect = %@", @1];
    StationInfoEntity *mainEntity = [StationInfoEntity MR_findFirstWithPredicate:predicateMain sortedBy:@"order" ascending:YES];
    return mainEntity;
}

//更新替换选中站点
- (void)updataStationEntity:(StationInfoEntity*)entity
{
    if(!entity) return;
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新
        StationInfoEntity *selectEntity = [self getSelectStationEntity];
        selectEntity.isSelect = [NSNumber numberWithBool:NO];
        entity.isSelect = [NSNumber numberWithBool:YES];
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        
        //通知页面更新
        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
        NSNotification *broadcastMessage = [NSNotification notificationWithName:StationInfoChangeKey object:entity];
        [notificationCenter postNotification:broadcastMessage];
    });
}

- (void)clearStationData
{
    NSArray *persons = [StationInfoEntity MR_findAll];
    for(StationInfoEntity *model in persons) [model MR_deleteEntity];
}

#pragma mark - 网络获取站点
- (void)startQueryService
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    if(!userInfo) return;
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"OTHER_YHZDHQ"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        if(result.resultArray && result.resultArray.count>0){
            [self clearStationData];//清理站点信息
            
            NSArray *resultValue = result.resultArray.firstObject;
            for(int i=0;i<resultValue.count;i++){
                NSDictionary *dictionary = resultValue[i];
                StationInfoEntity *person = [StationInfoEntity MR_createEntity];
                person.stationId = [dictionary objectFormatStringForKey:@"站点ID" defaults:@""];
                person.stationName = [dictionary objectFormatStringForKey:@"站点名称" defaults:@""];
                person.isSelect = [NSNumber numberWithBool:i==0];
                person.order = [NSNumber numberWithInteger:i];
            }
            //保存数据
            [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        //延迟5秒，重新查询数据
        __block GetUserStationService *weakSelf = self;
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [weakSelf startQueryService];
        });
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        //延迟5秒，重新查询数据
        __block GetUserStationService *weakSelf = self;
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [weakSelf startQueryService];
        });
    }];
}

@end
